﻿using MiniFox.Data.NativeClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MiniFox.Data.PostgreSql
{
    /// <summary>
    /// 
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class NpgSqlDataOperation<TEntity> : NativeDataOperation<TEntity> where TEntity : class
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="database"></param>
        public NpgSqlDataOperation(Database database) : base(database)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="incrementParameters"></param>
        /// <returns></returns>
        protected override string CreateAutoIncrementOutputExpression(IDictionary<string, string> incrementParameters)
        {
            string sqlstr = string.Empty;
            Type type = typeof(TEntity);
            foreach (var p in incrementParameters)
            {
                PropertyInfo property = type.GetProperty(p.Key);
                IncrementSequenceAttribute sequence = Attribute.GetCustomAttribute(property, typeof(IncrementSequenceAttribute)) as IncrementSequenceAttribute;
                if (sequence == null || string.IsNullOrWhiteSpace(sequence.SequenceName))
                    continue;

                sqlstr += $"SELECT currval('{this.FormatDatabaseObject(sequence.SequenceName)}' INTO {p.Value};\r";
            }
            return sqlstr;
        }
    }
}
